/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2024 All Rights Reserved.
 */
package com.alipay.demo.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.*;
import com.alipay.api.internal.util.StringUtils;
import com.alipay.api.request.AlipayOpenAppLocalitemCalendarpriceSaveRequest;
import com.alipay.api.request.AlipayOpenAppLocalitemCalendarstockSaveRequest;
import com.alipay.api.request.AlipayOpenAppLocalitemSpuSaveRequest;
import com.alipay.api.response.AlipayOpenAppLocalitemCalendarpriceSaveResponse;
import com.alipay.api.response.AlipayOpenAppLocalitemCalendarstockSaveResponse;
import com.alipay.api.response.AlipayOpenAppLocalitemSpuSaveResponse;
import com.alipay.api.response.AlipayOpenAppLocalitemTemplateQueryResponse;
import com.alipay.demo.service.AntMerchantShopService;
import com.alipay.demo.service.ImageUploadService;
import com.alipay.demo.service.LocalItemCalendarService;
import com.alipay.demo.service.LocalItemService;
import com.alipay.demo.util.AlipayApiCallback;
import com.alipay.demo.util.AlipayApiTemplate;
import com.alipay.demo.util.AlipaySdkUtil;
import com.alipay.demo.vo.LocalItemSpuRequest;
import com.alipay.demo.vo.OpenResponse;
import com.google.common.collect.Lists;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jishupei.jsp
 * @version : LocalItemCalendarServiceImpl, v0.1 2024年05月23日 11:31 上午 jishupei.jsp Exp $
 */
@Service
public class LocalItemCalendarServiceImpl implements LocalItemCalendarService {

    private static final Logger logger = LogManager.getLogger(LocalItemCalendarServiceImpl.class);

    @Autowired
    private AlipaySdkUtil alipaySdkUtil;

    @Autowired
    private LocalItemService localItemService;

    @Autowired
    private ImageUploadService imageUploadService;

    @Autowired
    private AntMerchantShopService antMerchantShopService;

    @Override
    public OpenResponse<String> saveSpu(LocalItemSpuRequest param) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<String, AlipayOpenAppLocalitemSpuSaveResponse>() {
            @Override
            public AlipayOpenAppLocalitemSpuSaveResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayOpenAppLocalitemSpuSaveRequest request = new AlipayOpenAppLocalitemSpuSaveRequest();
                AlipayOpenAppLocalitemSpuSaveModel model = new AlipayOpenAppLocalitemSpuSaveModel();

                // 设置标品名称
                model.setSpuName(param.getSpuName());

                // 设置类目ID
                model.setCategoryId(param.getCategoryId());

                // 设置外部标品id
                model.setOutSpuId(param.getOutSpuId());

                // 设置商品类型
                model.setItemType("7");

                // 设置状态
                if (!StringUtils.isEmpty(param.getSpuStatus())) {
                    model.setSpuStatus(param.getSpuStatus());
                }

                // 设置标品id
                if (!StringUtils.isEmpty(param.getSpuId())) {
                    model.setSpuId(param.getSpuId());
                }

                // 设置属性列表
                model.setAttrs(getItemAttrs(param, model.getItemType()));

                request.setBizModel(model);
                return alipaySdkUtil.execute(request);
            }

            @Override
            public String getData(AlipayOpenAppLocalitemSpuSaveResponse response) {
                return response.getSpuId();
            }

            @Override
            public String getApiName() {
                return "alipay.open.app.localitem.spu.save";
            }
        });
    }

    @Override
    public OpenResponse<Void> saveCalendarStock(String itemId, String outItemId, Long status) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<Void, AlipayOpenAppLocalitemCalendarstockSaveResponse>() {
            @Override
            public AlipayOpenAppLocalitemCalendarstockSaveResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayOpenAppLocalitemCalendarstockSaveRequest request = new AlipayOpenAppLocalitemCalendarstockSaveRequest();
                AlipayOpenAppLocalitemCalendarstockSaveModel model = new AlipayOpenAppLocalitemCalendarstockSaveModel();

                if (!StringUtils.isEmpty(itemId)) {
                    // 设置平台侧商品id
                    model.setItemId(itemId);
                }

                if (!StringUtils.isEmpty(outItemId)) {
                    // 设置商家侧商品id
                    model.setOutItemId(outItemId);
                }

                // 设置日历库存列表
                List<ItemCalendarStockVO> calendarStocksDZSFM = new ArrayList<>();
                ItemCalendarStockVO calendarStocksDZSFM0 = new ItemCalendarStockVO();
                // 库存的状态
                calendarStocksDZSFM0.setStatus(status == null ? 1 : status);
                // 第二天00:00:00开始
                calendarStocksDZSFM0.setStartDate(LocalDateTime.now()
                        .plusDays(1)
                        .format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                // 一个月后00:00:00结束
                calendarStocksDZSFM0.setEndDate(LocalDateTime.now()
                        .plusMonths(1)
                        .format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                calendarStocksDZSFM0.setStockLimit(1L);
                calendarStocksDZSFM0.setStockNum(100L);
                calendarStocksDZSFM.add(calendarStocksDZSFM0);
                model.setCalendarStocks(calendarStocksDZSFM);
                request.setBizModel(model);
                return alipaySdkUtil.execute(request);
            }

            @Override
            public Void getData(AlipayOpenAppLocalitemCalendarstockSaveResponse response) {
                return null;
            }

            @Override
            public String getApiName() {
                return "alipay.open.app.localitem.calendarstock.save";
            }
        });
    }

    @Override
    public OpenResponse<Void> saveCalendarPrice(String itemId, String outItemId, Long status) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<Void, AlipayOpenAppLocalitemCalendarpriceSaveResponse>() {
            @Override
            public AlipayOpenAppLocalitemCalendarpriceSaveResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayOpenAppLocalitemCalendarpriceSaveRequest request = new AlipayOpenAppLocalitemCalendarpriceSaveRequest();
                AlipayOpenAppLocalitemCalendarpriceSaveModel model = new AlipayOpenAppLocalitemCalendarpriceSaveModel();

                if (!StringUtils.isEmpty(itemId)) {
                    // 设置平台侧商品id
                    model.setItemId(itemId);
                }

                if (!StringUtils.isEmpty(outItemId)) {
                    // 设置商家侧商品id
                    model.setOutItemId(outItemId);
                }

                // 设置日历价格列表
                List<ItemCalendarPriceVO> calendarPricesDLzON = new ArrayList<>();
                ItemCalendarPriceVO calendarPricesDLzON0 = new ItemCalendarPriceVO();
                calendarPricesDLzON0.setStatus(status == null ? 1 : status);
                // 第二天00:00:00开始
                calendarPricesDLzON0.setStartDate(LocalDateTime.now()
                        .plusDays(1)
                        .format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                // 一个月后00:00:00结束
                calendarPricesDLzON0.setEndDate(LocalDateTime.now()
                        .plusMonths(1)
                        .format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                calendarPricesDLzON0.setOriginalPrice(20000L);
                calendarPricesDLzON0.setSalePrice(10000L);
                calendarPricesDLzON.add(calendarPricesDLzON0);
                model.setCalendarPrices(calendarPricesDLzON);

                request.setBizModel(model);
                return alipaySdkUtil.execute(request);
            }

            @Override
            public Void getData(AlipayOpenAppLocalitemCalendarpriceSaveResponse response) {
                return null;
            }

            @Override
            public String getApiName() {
                return "alipay.open.app.localitem.calendarprice.save";
            }
        });
    }

    private List<AppItemAttrVO> getItemAttrs(LocalItemSpuRequest param, String itemType) throws AlipayApiException {
        List<AppItemAttrVO> attrs = new ArrayList<>();
        OpenResponse<AlipayOpenAppLocalitemTemplateQueryResponse> templateResponse = localItemService.queryTemplate(param.getCategoryId(), itemType);
        if (!"10000".equals(templateResponse.getCode())) {
            logger.error("查询本地商品模板失败");
            return attrs;
        }
        List<AttributeVO> attributes = templateResponse.getData().getAttr().getSpuAttrList();
        if (CollectionUtils.isEmpty(attributes)) {
            return attrs;
        }
        for (AttributeVO attr : attributes) {
            if (!attr.getIsRequired()) {
                continue;
            }
            AppItemAttrVO appItemAttrVO = new AppItemAttrVO();
            appItemAttrVO.setAttrKey(attr.getKey());
            switch (attr.getKey()) {
                case "image_list":
                    // 封面图
                    List<String> imageList = new ArrayList<>();
                    imageList.add(imageUploadService.uploadAndReturnId("file/head.jpg", "ITEM_HEAD_IMG"));
                    appItemAttrVO.setAttrValue(JSONArray.toJSONString(imageList));
                    break;
                case "shop_list":
                    // 门店id列表
                    if (CollectionUtils.isEmpty(param.getShopIds())) {
                        // 不存在则取所有正常状态的门店
//                        List<String> collect = antMerchantShopService.queryNormalShopInfos().stream()
//                                .map(ShopQueryOpenApiVO::getShopId).collect(Collectors.toList());
                        // 不存在则取第一条正常状态的门店
                        List<ShopQueryOpenApiVO> vos = antMerchantShopService.queryNormalShopInfos();
                        List<String> collect = vos.isEmpty() ? new ArrayList<>() : Lists.newArrayList(vos.get(0).getShopId());
                        appItemAttrVO.setAttrValue(JSONArray.toJSONString(collect));
                    } else {
                        appItemAttrVO.setAttrValue(JSONArray.toJSONString(param.getShopIds()));
                    }
                    break;
                case "room_num":
                    // 总间数
                    appItemAttrVO.setAttrValue("123");
                    break;
                case "floor":
                    // 楼层
                    appItemAttrVO.setAttrValue("1层,3-5层");
                    break;
                case "area":
                    // 面积
                    appItemAttrVO.setAttrValue("10-30");
                    break;
                case "window_type":
                    // 窗型，无窗:0;有窗:1;部分有窗:2;暗窗:3;部分暗窗:4
                    appItemAttrVO.setAttrValue("2");
                    break;
                case "bed_type":
                    // 床型，大床;双床;单人床;榻榻米等
                    appItemAttrVO.setAttrValue("大床");
                    break;
                case "bed_size":
                    // 床宽
                    appItemAttrVO.setAttrValue("2.0米");
                    break;
                case "max_occupancy":
                    // 最大入住人（1-99）
                    appItemAttrVO.setAttrValue("2");
                    break;
                case "smoke":
                    // 吸烟政策，可吸烟:0;不可吸烟:1;部分房间可吸烟:2"
                    appItemAttrVO.setAttrValue("1");
                    break;
            }

            attrs.add(appItemAttrVO);
        }
        return attrs;
    }

    /**
     * 获取本地商品标品属性模板信息
     */
    public List<AttributeVO> queryTemplateSpuAttrList(String categoryId, String itemType) {

        return null;
    }
}
